/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-14 17:39:31
 * @Description  : 章节接口控制器
 */
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const { Chapter, Exam } = require('@/models/model')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { delModel, sortModel } = require('@/utils/controllerCommon')

/**
 * 列表查询章节接口
 * @param {*} ctx
 * @returns
 */
module.exports.listChapter = async (ctx) => {
  const orderCondition = [['sort']]
  const { page, pageSize, pid, examId } = ctx.query
  const start = (page - 1) * pageSize
  const whereCondition = {}
  if (examId !== undefined) {
    whereCondition.examId = examId
  }
  if (pid !== undefined) {
    whereCondition.pid = pid
  }
  const { rows, count } = await Chapter.findAndCountAll({
    where: whereCondition,
    offset: +start,
    include: [
      {
        model: Chapter,
        as: 'ParentChapter'
      },
      {
        model: Exam
      }
    ],
    limit: +pageSize,
    order: orderCondition,
    distinct: true
  })

  // for (let i = 0; i < rows.length; i++) {
  //   const curRows = [rows[i]]
  //   const final = []
  //   const queue = curRows.map((item) => {
  //     return {
  //       ...item.dataValues,
  //       isLeaf: false
  //     }
  //   })
  //   while (queue.length) {
  //     const a = queue.shift()
  //     const { rows, cnt } = await Chapter.findAndCountAll({
  //       where: {
  //         pid: a.id
  //       },
  //       include: [
  //         {
  //           model: Chapter,
  //           as: 'ParentChapter'
  //         },
  //         {
  //           model: Exam
  //         }
  //       ],
  //       order: orderCondition,
  //       distinct: true
  //     })

  //     if (!cnt) {
  //       a.isLeaf = true
  //       final.push(a)
  //     } else {
  //       queue.push(
  //         ...rows.map((item) => {
  //           return {
  //             ...item.dataValues,
  //             isLeaf: false
  //           }
  //         })
  //       )
  //     }
  //   }

  //   // 得到所有的叶子章节，得到叶子章节的所有试卷
  // }

  // 需要判断是否为叶子节点
  for (let i = 0; i < rows.length; i++) {
    let a = rows[i]
    const cnt = await Chapter.count({
      where: {
        pid: a.id
      }
    })
    a.dataValues.childLen = cnt
  }

  ctx.body = R.success({
    page,
    pageSize,
    total: count,
    pages: Math.ceil(count / pageSize),
    items: rows
  })
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 创建章节接口
 * @param {*} ctx
 */
module.exports.createChapter = async (ctx) => {
  const { examId, pid, name } = ctx.request.body
  const t = await Mysequelize.transaction()
  const nextId = generatId()
  const sort = await Chapter.max('sort')

  let createObj = {
    id: nextId,
    name,
    pid,
    examId,
    sort: sort + 1,
    createUser: ctx.user.id,
    updateUser: ctx.user.id
  }

  try {
    // 到这里可以进行章节的添加了,排序字段默认是最大值
    const chapter = await Chapter.create(createObj, {
      transaction: t
    })
    await t.commit()
    ctx.body = R.success()
  } catch (error) {
    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.CHAPTER_CREATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 更新章节接口
 * @param {*} ctx
 */
module.exports.updateChapter = async (ctx) => {
  const t = await Mysequelize.transaction()
  const { chapterId, name, pid, examId } = ctx.request.body
  const updateObj = {
    name
  }
  if (pid) {
    updateObj.pid = pid
  }

  if (examId) {
    updateObj.examId = examId
  }

  try {
    // 进行章节信息的更新
    await Chapter.update(updateObj, {
      where: {
        id: BigInt(chapterId)
      },
      transaction: t
    })
    await t.commit()
    ctx.body = R.success()
  } catch (e) {
    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.CHAPTER_UPDATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除章节接口
 * @param {*} ctx
 */
module.exports.delChapters = async (ctx) => {
  await delModel(Chapter, ERROR_USER_CODE.CHAPTER_DEL_ERROR, 'chapterIds')(ctx)
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 章节排序接口
 * @param {*} ctx
 */
module.exports.sortChapters = async (ctx) => {
  // 传递的章节ID顺序即为排序顺序，取出这些ID对应的sort，sort从小到大排序后，依次赋值
  await sortModel(
    Chapter,
    ERROR_USER_CODE.CHAPTER_SORT_ERROR,
    'chapterIds'
  )(ctx)
}
